<?php
declare(strict_types=1);
// 确保文件使用 UTF-8 编码

namespace payment;

use app\common\service\ConfigService;

use think\facade\Config;
use think\facade\Log;

class SlashService
{

    private $slashCookie;
    public $apiKey;

    private $cardGroupId;

    public function __construct($slashType = 12)
    {
        //动态获取slash配置
        if($slashType == 12){
            $slashConfig = 'slash';
        }else{
            $slashConfig = 'slash_'.$slashType;
        }

        $this->slashCookie = ConfigService::get('slash', 'cookie');
        $this->apiKey = Config::get($slashConfig.'.api_key');
        $this->cardGroupId = Config::get($slashConfig.'.card_group_id');
    }

    /**
     * 通用请求方法
     * @param string $url 请求URL
     * @param string $method 请求方法
     * @param array|null $data 请求数据
     * @param int $timeout 超时时间
     * @return array|false
     */
    private function slash_request($url, $method = 'GET', $data = null, $timeout = 30)
    {
        $headers = [
            "accept: application/vnd.slash.user.v1+json",
            "accept-language: zh-CN,zh;q=0.9",
            "content-type: application/vnd.slash.user.v1+json",
            "origin: https://app.slash.com",
            "referer: https://app.slash.com/platinum/cards",
            "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36",
            "x-slash-client-platform: Web",
            "x-slash-request-new-response-format: PLEASE",
            "x-user-timezone: Asia/Shanghai"
        ];

        trace($url);
        Log::error("SlashService请求地址: " . $url);

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_COOKIE, 'slash:session=' . $this->slashCookie);
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);

        if (strtoupper($method) === 'PATCH') {
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH");
            if ($data !== null) {
                trace($data);
                curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
            }
        } elseif (strtoupper($method) === 'POST') {
            curl_setopt($curl, CURLOPT_POST, true);
            if ($data !== null) {
                curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
            }
        }
        $response = curl_exec($curl);
        trace($response);
        $err = curl_error($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);

        if ($err) {
            Log::error("SlashService::slash_request 请求异常: " . $err);
            return false;
        }
        if ($httpCode < 200 || $httpCode >= 300) {
            Log::error("SlashService::slash_request HTTP错误: " . $httpCode . ", 响应: " . $response);
            return false;
        }
        $data = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            Log::error("SlashService::slash_request 响应JSON解析失败: " . $response);
            return false;
        }
        return $data;
    }

    /**
     * 获取卡片详情
     * @param string $cardId 卡片ID
     * @return array|false
     */
    public function getCardDetails($cardId)
    {
        $url = "https://app.slash.com/api/v2/cards/{$cardId}/details";
        return $this->slash_request($url, 'GET');
    }

    /**
     * 更新卡片限额
     * @param string $cardId 卡片ID
     * @param array $limitData 限额数据
     * @return array|false
     */
    public function updateCardLimit($cardId, $limitData)
    {
        $url = "https://app.slash.com/api/v2/cards/{$cardId}";
        return $this->slash_request($url, 'PATCH', $limitData);
    }

    /**
     * 获取卡片限额
     * @param string $cardId 卡片ID
     * @return array|false
     */
    public function getCardLimit($cardId)
    {
        $url = "https://app.slash.com/api/v2/cards/{$cardId}";
        return $this->slash_request($url, 'GET');
    }

    /**
     * 设置卡片限额
     * @param string $cardId 卡片ID
     * @param string $preset 限额类型，可选值：daily(每日), weekly(每周), monthly(每月), yearly(每年), total(总限额)
     * @param int $amountCents 限额金额（美分）
     * @param string $currency 货币类型，默认USD
     * @return array|false
     */
    public function setCardLimit($cardId, $preset, $amountCents, $currency = 'USD')
    {
        // 验证限额类型
        $validPresets = ['daily', 'weekly', 'monthly', 'yearly', 'total'];
        if (!in_array($preset, $validPresets)) {
            Log::error("SlashService::setCardLimit 无效的限额类型: " . $preset);
            return false;
        }

        $limitData = [
            'spendingRule' => [
                'spendingRule' => [
                    'utilizationLimit' => [
                        'limitAmount' => [
                            'amount_cents' => $amountCents,
                            'currency' => $currency
                        ],
                        'preset' => $preset
                    ],
                    'utilizationLimitV2' => [
                        [
                            'limitAmount' => [
                                'amount_cents' => $amountCents,
                                'currency' => $currency
                            ],
                            'preset' => $preset
                        ]
                    ]
                ]
            ]
        ];
        return $this->updateCardLimit($cardId, $limitData);
    }

    /**
     * 更新卡片状态
     * @param array $assetId 卡片ID
     * @param string $operateType 操作类型可取值范围：
     *  pause：冻结卡片
     *  unpause：解冻卡片
     *  delete：删除卡片
     * @return array
     */
    public function updateCardStatus($assetId, $operateType)
    {
        if (is_string($assetId))
            $assetId = [$assetId];
        if (!in_array($operateType, ['pause', 'unpause', 'delete'])) {
            return ['code' => 400, 'msg' => '操作类型错误'];
        }

        $data = [
            'action' => $operateType,
            'cards' => [
                'globalSelect' => false,
                'ids' => $assetId
            ]
        ];
        $url = "https://app.slash.com/api/v2/account/sa_group_cb3cefunuffy/cards";
        return $this->slash_request($url, 'PATCH', $data);
    }

    //下面为api对接方式
    function request($url, $method = 'GET', $data = [])
    {
        if ($method == 'GET' && !empty($data)) {
            $query = http_build_query($data);
            $url = $url . '?' . $query;
        }

//        trace($url);
//        trace($data);

        $headers = [
            "X-API-Key: " . $this->apiKey,
            "Content-Type: application/json"
        ];
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36");

        if (strtoupper($method) === 'PATCH') {
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH");
            if ($data !== null) {
                curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
            }

        } elseif (strtoupper($method) === 'POST') {
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
            if ($data !== null) {
                curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
            }
        }
        $response = curl_exec($curl);
        curl_close($curl);
//        trace($response);
        return $response;
    }

    //创建卡片
    public function createCard($cardGroupId = '')
    {
        $params = [
//            "accountId" => "sa_group_2ze0lzwoxaejo",
//            "virtualAccountId" => "subaccount_3lyuesvdgngc4",
            "type" => "virtual",
            "name" => "",
            "isSingleUse" => false,
            "cardGroupId" => $cardGroupId,
        ];

        $result = $this->request('https://api.joinslash.com/card', 'POST', $params);
        $result = json_decode($result, true);
        return $result;
    }

    //获取卡片列表
    public function getCardList($params = [])
    {
        $result = $this->request('https://api.joinslash.com/card', 'GET', $params);
        $result = json_decode($result, true);

        return $result;
    }

    //获取交易记录列表
    public function getTransaction($params = [])
    {
        $result = $this->request('https://api.joinslash.com/transaction', 'GET', $params);
        $result = json_decode($result, true);

        return $result;
    }

    //获取卡片敏感信息
    public function getCardInfo($cardId, $secure = false)
    {
        $url = "https://vault.joinslash.com/card/{$cardId}";
        $params = [];
        if ($secure) {
            $params = [
                'include_pan' => 'true',
                'include_cvv' => 'true'
            ];
        }

        $result = $this->request($url, 'GET', $params);
        $result = json_decode($result, true);

        return $result;
    }

    //获取卡片使用率
    public function getCardUtilization($cardId)
    {
        $url = "https://api.joinslash.com/card/{$cardId}/utilization";
        $result = $this->request($url, 'GET');
        $result = json_decode($result, true);
        return $result;
    }

    //更新卡状态
    public function setCardStatus($cardId, $status)
    {
        $url = "https://api.joinslash.com/card/{$cardId}";
        $result = $this->request($url, 'PATCH', ['status' => $status]);
        $result = json_decode($result, true);

        return $result;
    }

    //更新卡消费规则
    public function setCardRule($cardId, $preset, $amountCents, $single)
    {
        $limitData = [];
        // 验证限额类型
        $validPresets = ['daily', 'weekly', 'monthly', 'yearly', 'collective'];
        if (in_array($preset, $validPresets)) {
            $limitData['utilizationLimit'] = [
                'limitAmount' => [
                    'amountCents' => $amountCents,
                ],
                'preset' => $preset
            ];

        }
        if ($single > 0) {
            $limitData['transactionSizeLimit'] = [
                'maximum' => [
                    'amountCents' => $single,
                ],
            ];
        }

        if (empty($limitData)) return false;

        $url = "https://api.joinslash.com/card/{$cardId}/spending-constraint";
        $result = $this->request($url, 'PATCH', ['spendingRule' => $limitData]);
        $result = json_decode($result, true);

        return $result;
    }

    //获取卡片组

    public function getCardGroup($params = [])
    {
        $result = $this->request('https://api.joinslash.com/card-group', 'GET', $params);
        $result = json_decode($result, true);
        return $result;
    }


    //创建卡片组
    public function createCardGroup($name)
    {
        if ($name == '') return false;
        $params = [
            'name' => $name,
            'virtualAccountId' => 'subaccount_3lyuesvdgngc4',
            'spendingConstraint' => [
                'merchantCategoryRule' => [
                    'merchantCategories' => ['merchant_category_2vd5uhcjvdbvz'],
                    'restriction' => 'allowlist'
                ],
            ]
        ];
        $result = $this->request('https://api.joinslash.com/card-group', 'POST', $params);
        $result = json_decode($result, true);
        return $result;
    }
}